﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text.RegularExpressions;


public partial class Business_Cisoft3G_ContactsManage_ContactAdd : WebUI.Page.BasePage
{

    public static bool MobileIsR = false;

    #region 页面加载
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindContactGroup();
        }
    }
    #endregion

    #region 填充实体类 ContactsMO FillModel()
    /// <summary>
    /// 填充实体类
    /// </summary>
    /// <returns></returns>
    private Cisoft.Cisoft3G.Model.ContactsMO FillModel()
    {
        Cisoft.Cisoft3G.Model.ContactsMO model = new Cisoft.Cisoft3G.Model.ContactsMO();
        if (Page.IsValid)
        {
            model.CT_ContactID = new Cisoft.Cisoft3G.BLL.ContactsBO().GetMaxId();
            model.CT_Address = txtAddress.Text.Trim();
            model.CT_Company = txtCompany.Text.Trim();
            model.CT_CompanyAddress = txtCompanyAddress.Text.Trim();
            model.CT_Department = txtDepartment.Text.Trim();
            model.CT_Duty = txtDuty.Text.Trim();
            model.CT_Email = txtEmail.Text.Trim();
            model.CT_Mobile = txtMobile.Text.Trim();
            model.CT_Name = txtName.Text.Trim();
            model.CT_Phone = txtPhone.Text.Trim();
            model.CT_PostCode = txtPostCode.Text.Trim();
            model.CT_QQ = txtQQ.Text.Trim();
            model.CT_Sex = 1;
            model.CT_Mobile2 = "";
            model.CG_ContactGroupID_FK = int.Parse(ddlContactGroup.SelectedValue);
            model.CT_IsUser = 0;
        }

        return model;
    }
    #endregion

    #region 返回事件
    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("ContactsManage.aspx");
    }
    #endregion

    #region 新增事件
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        string strError = string.Empty;
        Cisoft.Cisoft3G.BLL.ContactsBO bll = new Cisoft.Cisoft3G.BLL.ContactsBO();
        //获得实体类
        Cisoft.Cisoft3G.Model.ContactsMO model = FillModel();

        //手机号码验证
        Regex reg = new Regex(@"^15[0-9]{1}\d{8}|13\d{9}|18[6789]{1}\d{8}$");
        if (reg.IsMatch(model.CT_Mobile.Trim()))
        {
            try
            {
                //验证手机号码是否重复
                if (bll.MobileIsExsist(txtMobile.Text.Trim()) > 0)
                {
                    PageError(ModalPopupExtender2, lblTS, btnBack_ts, "<h4>该手机号码已经在通讯录中！</h4>", Request.RawUrl);
                    return;
                }
                else
                {
                    //添加至联系人表
                    bll.Add(model);
                    //添加至管理员表
                    AddToUserTable(model.CT_Mobile, model.CT_Name);
                }
            }
            catch (Exception ex)
            {
                strError = ex.Message;
            }
            if (!string.IsNullOrEmpty(strError))
            {
                PageError(ModalPopupExtender2, lblTS, btnBack_ts, "新增联系人失败！失败原因如下：" + strError, Request.RawUrl);
                //PageError("新增联系人失败！失败原因如下：" + strError + "。", Request.RawUrl);

                //string scriptStr = "location.replace(" + Server.HtmlEncode(" '../CustomRedrect.aspx?Type=False&Message=新增联系人失败！失败原因如下：" + strError + "&Url=ContactsManage/ContactsManage.aspx'") + ")";
                //ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "click", scriptStr, true);
            }
            else
            {
                PageRight(ModalPopupExtender2, lblTS, btnBack_ts, "<h4>新增联系人成功！</h4>", "ContactsManage.aspx");
                //PageRight("新增联系人成功！", "ContactsManage.aspx", "点击返回", "");
                //string scriptStr = "location.replace(" + Server.HtmlEncode(" '../CustomRedrect.aspx?Type=Success&Message=新增联系人成功!&Url=ContactsManage/ContactsManage.aspx'") + ")";
                //ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "click", scriptStr, true);
            }
        }
        else
        {
            PageError(ModalPopupExtender2, lblTS, btnBack_ts, "<h4>该号码不是有效的手机号码！</h4>",Request.RawUrl);
            return;
        }
    }
    #endregion

    #region 绑定联系人组
    private void BindContactGroup()
    {
        ShowColumns(ddlContactGroup, 0, 0, "CG_ContactGroupID", "CG_ParentID", "CG_GroupName", "CG_ContactGroup");
    }
    #endregion

    #region 下拉框显示树型

    /// <summary>
    /// 组合框显示所有级别（无限级级别）
    /// </summary>
    /// <param name="dropList">组合框名称</param>
    /// <param name="iDepth">深度</param>
    ///  <param name="iParentID">父类ID</param>int iParentID
    public void ShowColumns(DropDownList dropList, int iDepth, int iParentID, string id, string pid, string name, string tableName)
    {
        //定义变量
        int iCount = 0;
        int iSum = 0;
        string strGroupName = "";
        string strGroupID = "";
        DataSet ds = new DataSet();

        ds = new Cisoft.Cisoft3G.BLL.ContactGroupBO().GetList(" " + pid + "=" + iParentID + " order by cg_order desc");

        iCount = ds.Tables[0].Rows.Count;

        if (iCount != 0)
        {
            //iSum深度处理
            iSum = iDepth + 1;

            for (int i = 0; i < iCount; i++)
            {
                if (i == (iCount - 1))
                {
                    strGroupName = replaceWord(GetDepth("┗" + ds.Tables[0].Rows[i][name].ToString(), iSum));
                    strGroupID = ds.Tables[0].Rows[i][id].ToString();

                    dropList.Items.Add(new ListItem(strGroupName, strGroupID));
                }
                else
                {
                    strGroupName = replaceWord(GetDepth("┗" + ds.Tables[0].Rows[i][name].ToString(), iSum));
                    strGroupID = ds.Tables[0].Rows[i][id].ToString();

                    dropList.Items.Add(new ListItem(strGroupName, ds.Tables[0].Rows[i][id].ToString()));
                }
                ShowColumns(dropList, iSum, Int32.Parse(ds.Tables[0].Rows[i][id].ToString()), id, pid, name, tableName);
            }
        }
    }

    /// <summary>
    /// 字符串插入"│"字符
    /// </summary>
    /// <param name="str">需要插入"│"的字符串</param>
    /// <param name="i">插入"│"字符串的索引位置</param>
    /// <returns></returns>
    private static string GetDepth(string strGroupName, int iCount)
    {
        for (int i = 1; i < iCount; i++)
        {
            strGroupName = strGroupName.Insert(0, "│");
        }

        return strGroupName;
    }

    /// <summary>
    /// 将指定字符串里的“&nbsp;”替换为空字符
    /// </summary>
    /// <param name="strText"></param>
    /// <returns></returns>
    private string replaceWord(string strText)
    {
        string outText = strText.Replace("&nbsp;", " ");
        return outText;
    }

    #endregion

    #region 新增至管理员表
    private void AddToUserTable(string mobile, string realname)
    {
        string xmlPath = Server.MapPath(Request.ApplicationPath + "/xmlconfig/sys/cis.config");
        string roleid = Cisoft.IntegrationSystem.Common.XMLHelper.GetConfigValue("cisDefaultMemberRole", xmlPath);

        Cisoft.IntegrationSystem.BLL.UserBO userBll = new Cisoft.IntegrationSystem.BLL.UserBO();
        Cisoft.IntegrationSystem.Model.UserMO userModel = new Cisoft.IntegrationSystem.Model.UserMO();
        Cisoft.IntegrationSystem.BLL.UserInfoBO uiBll = new Cisoft.IntegrationSystem.BLL.UserInfoBO();
        Cisoft.IntegrationSystem.Model.UserInfoMO uiModel = new Cisoft.IntegrationSystem.Model.UserInfoMO();

        int id = userBll.GetMaxID();
        userModel.UserID = id;
        userModel.UserGroupID = 0;
        userModel.UserName = string.Format("CG_{0}", DateTime.Now.ToString("yyyyMMddHHmmss"));
        userModel.UserPassword = new Cisoft.IntegrationSystem.Common.MD5().HashString("123456");
        userModel.UserRealName = realname;
        userModel.Userrole = int.Parse(roleid);
        userModel.UserApplyDate = DateTime.Now;

        uiModel.UI_UserID_FK = id;
        uiModel.UI_JoblName = "";
        uiModel.UI_Phone = mobile;

        try
        {
            userBll.AddRecord(userModel);
            uiBll.Add(uiModel);
        }
        catch (Exception ex)
        {

            throw;
        }
    }
    #endregion

}
